import os

from utils.propertiesUtil import PropertiesUtil


class Config(object):
    """ Base Config 基础配置类
    """
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))
    BASE_DB_DIR = os.path.dirname(os.path.dirname(__file__)+"\db")

    SANIC_ENV = "Prod"
    DEBUG = False
    SERVER_HOST = "0.0.0.0"
    SERVER_PORT = 8000
    DB_ECHO = True

    DB_TYPE = "sqlite"
    # sqlite 数据库
    DB_FILE = "sanic.db"
    # TRUE:跟踪数据库变更并记录;FALSE:不记录
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    TIMEZONE = 'Asia/Shanghai'

    # ALEMBIC
    # ALEMBIC_CONFIG_PATH = os.getenv('ALEMBIC_CONFIG_PATH', os.path.join(os.path.dirname(BASE_DIR), 'alembic.ini'))
    ALEMBIC_CONFIG_PATH = os.path.join(BASE_DIR, 'alembic.ini')
    # ALEMBIC_MIGRATIONS_PATH = os.getenv('ALEMBIC_MIGRATIONS_PATH',os.path.join(os.path.join(BASE_DIR), 'alembic'))
    ALEMBIC_MIGRATIONS_PATH = os.path.join(BASE_DIR, 'alembic')

    LOG_FILE = "logs/app-sanic-server.log"
    LOG_REMAIN = 30

    SWAGGER_API_TITLE="在线分析"
    SWAGGER_API_VERSION='0.0.1'

    CACHE=True
    CACHE_SIZE=120
    CACHE_TTL=600


    @classmethod
    def load_config(cls, config_file):
        """
        :param config_file:
        :return:
        """
        config = {}
        # 加载配置文件里的所有配置
        properties = PropertiesUtil(config_file).get_properties()

        # 加载当前定义的所有默认配置
        for field, value in iter(cls.__dict__.items()):
            if field.isupper():
                # print(field,value)
                config[field] = properties.pop(field.lower(), value)

        # 加载 properties 文件配置
        for field, value in properties.items():
            if field == "sanic_env":
                config['SANIC_ENV'] = value

            if field == 'server':
                config['SERVER_HOST'] = value.get("host", "0.0.0.0")
                config['SERVER_PORT'] = value.get("port", 8000)

            # 加载日志文件输出配置
            if field == "log":
                log_file = value.get("file", "logs/app-sanic-server.logs")
                if log_file.startswith("/"):
                    config['LOG_FILE'] = log_file
                else:
                    config['LOG_FILE'] = os.path.join(config['BASE_DIR'],log_file)

                config['LOG_REMAIN'] = value.get("remain", 14)

            # 加载数据库配置
            if field == 'db' and config['DB_TYPE'] == "sqlite":
                db_path = value.get("file", config['DB_FILE'])
                if db_path.startswith("/"):
                    config['DB_FILE'] = db_path
                else:
                    config['DB_FILE'] = os.path.join(config['BASE_DIR'],'db', db_path)


        config['DB_URI'] = "sqlite:///{}".format(config['DB_FILE'])
        # 清理无用的数据库连接配置[列表推导式]
        # [config.pop(i) for i in ('DB_HOST','DB_PORT','DB_DATABASE')]
        return config